package NIO;

import org.junit.Test;

import java.io.File;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

/**
 * @author VX5
 * @Title: MJC
 * @ProjectName DataStructure
 * @Description: TODO
 * @date ${DAT}16:17
 */
public class TestBlockingNIO2 {
    //客户端
    @Test
    public void client() throws IOException {
        SocketChannel sChannel = SocketChannel.open(new InetSocketAddress("127.0.0.1",9898));

        FileChannel inChannel = FileChannel.open(Paths.get("C:\\Users\\VX5\\Desktop\\图片1.png"), StandardOpenOption.READ);

        ByteBuffer buffer = ByteBuffer.allocate(1024);

        while (inChannel.read(buffer) != -1){
            buffer.flip();
            sChannel.write(buffer);
            buffer.clear();
        }

        sChannel.shutdownOutput();

        //接受服务端反馈
        int len = 0;
        while (sChannel.read(buffer) != -1){
            buffer.flip();
            System.out.println(new String(buffer.array(),0,len));
            buffer.clear();
        }

        inChannel.close();
        sChannel.close();
    }

    //服务端
    @Test
    public void server() throws IOException {
        ServerSocketChannel ssChannel = ServerSocketChannel.open();

        FileChannel fileChannel = FileChannel.open(Paths.get("C:\\Users\\VX5\\Desktop\\图片3.png"), StandardOpenOption.WRITE, StandardOpenOption.CREATE);

        ssChannel.bind(new InetSocketAddress(9898));

        SocketChannel socketChannel = ssChannel.accept();

        ByteBuffer buf = ByteBuffer.allocate(1024);
        while (socketChannel.read(buf) != -1){
            buf.flip();
            fileChannel.write(buf);
            buf.clear();
        }

        //发送反馈给客户端
        buf.put("接受数据成功".getBytes());
        buf.flip();
        socketChannel.write(buf);

    }
}
